//
//  SettingsViewController.swift
//  Git@OSC
//
//  Created by AeternChan on 9/1/15.
//  Copyright (c) 2015 oschina. All rights reserved.
//

import UIKit
import Mustache

class SettingsViewController: UITableViewController {
    
    @IBOutlet weak var styleLabel: UILabel!
    @IBOutlet weak var linenumbersSwitch: UISwitch!
    @IBOutlet weak var webView: UIWebView!
    
    var userDefaults = NSUserDefaults.standardUserDefaults()

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        styleLabel.text = userDefaults.objectForKey("style") as? String
        
        linenumbersSwitch.on = userDefaults.boolForKey("linenumbers")
        linenumbersSwitch.addTarget(self, action: "toggleLinenumbers", forControlEvents: .ValueChanged)
        
        webView.scrollView.scrollEnabled = false
        
        renderSample()
    }
    
    func toggleLinenumbers() {
        userDefaults.setBool(linenumbersSwitch.on, forKey: "linenumbers")
        
        renderSample()
    }
    
    func renderSample() {
        let template = try! Template(named: "file_content")
        let path = NSBundle.mainBundle().pathForResource("sample", ofType: "")
        let sample = try? String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
        let data: [String: AnyObject] = [
            "content": (sample?.escapeHTMLTag())!,
            "style": styleLabel.text!,
            "linenumbers": linenumbersSwitch.on
        ]
        let rendering = try! template.render(Box(data))
        webView.loadHTMLString(rendering, baseURL: NSBundle.mainBundle().resourceURL)
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
}
